package com.chixing.ih.module.task.service.impl;

import com.chixing.ih.module.programmer.mapper.ImageMapper;
import com.chixing.ih.module.programmer.mapper.ProgrammerMapper;
import com.chixing.ih.module.programmer.pojo.Programmer;
import com.chixing.ih.module.programmer.pojo.UserImage;
import com.chixing.ih.module.programmer.pojo.dto.ProgrammerCompareDTO;
import com.chixing.ih.module.programmer.pojo.dto.ProgrammerEntiretyDTO;
import com.chixing.ih.module.programmer.service.IProgrammerCompareService;
import com.chixing.ih.module.programmer.service.Impl.ProgrammerListServiceImpl;
import com.chixing.ih.module.system.pojo.ToEmail;
import com.chixing.ih.module.system.pojo.User;
import com.chixing.ih.module.task.mapper.TaskMapper;
import com.chixing.ih.module.task.pojo.Contract;
import com.chixing.ih.module.task.pojo.DTO.ContractDTO;
import com.chixing.ih.module.task.pojo.DTO.TaskDTO;
import com.chixing.ih.module.task.pojo.DTO.TaskShowDTO;
import com.chixing.ih.module.task.pojo.Order;
import com.chixing.ih.module.task.pojo.Task;
import com.chixing.ih.module.task.service.IOrderService;
import com.chixing.ih.module.task.service.ITaskService;
import com.chixing.ih.util.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 目的:
 *
 * @author ：zcw
 * @version: 1.0  2020/9/29 19:11
 */
@Service
@Transactional
public class TaskServiceImpl implements ITaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private ProgrammerMapper programmerMapper;

    @Autowired
    private IProgrammerCompareService iProgrammerCompareService;

    @Autowired
    private ProgrammerListServiceImpl programmerListService;

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private ITaskService iTaskService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private MailUtil mailUtil;

    private static String dataMap = "IT_refreshing";

    @Autowired
    private static RedisTemplate<String, Object> redisTemplate;

    public TaskServiceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public int insertOne(Task task) {
        task.setUpdateTime(new Date());
        return taskMapper.insertOne(task);
    }

    @Override
    public int deleteOne(Long taskId) {
        TaskShowDTO dto = taskService.findOne(taskId);
        int one = taskMapper.deleteOne(taskId);
        return one;
    }

    @Override
    public int deleteAll(Long userId) {
        return taskMapper.deleteAll(userId);
    }

    @Override
    public int updateOne(Task task) {
        return taskMapper.updateOne(task);
    }





    @Override
    public TaskShowDTO findOne(Long id) {

        TaskShowDTO task = taskMapper.findOne(id);
        if (null != task) {
            User user = taskMapper.findByTaskId(id);
            task.setNickName(user.getNickName()).setUserId(user.getUserId()).setEmail(user.getUserEmail());
            UserImage image = imageMapper.getOneByUserId(task.getIsSuerId());
            if (null != image) {
                task.setImgUrl(image.getImageUrl());
            } else {
                task.setImgUrl("http://masteryan.oss-cn-beijing.aliyuncs.com/1000000740998476.png");
            }
            return task;
        }
        return null;
    }

    @Override
    public TaskShowDTO findTaskOne(Long id) {
        TaskShowDTO task = taskMapper.findTaskOne(id);
        if (null != task) {
            User user = taskMapper.findByTaskId(id);
            task.setNickName(user.getNickName()).setUserId(user.getUserId()).setEmail(user.getUserEmail());
            UserImage image = imageMapper.getOneByUserId(task.getIsSuerId());
            if (null != image) {
                task.setImgUrl(image.getImageUrl());
            } else {
                task.setImgUrl("http://masteryan.oss-cn-beijing.aliyuncs.com/1000000740998476.png");
            }
            return task;
        }
        return null;
    }

    @Override
    public List<TaskShowDTO> findAccepting(PageRequest pageRequest, Long userId) {
        if (EmptyUtil.isEmpty(pageRequest.getPageNum())) {
            pageRequest.setPageNum(1);
        }

        if (EmptyUtil.isEmpty(pageRequest.getPageSize())) {
            pageRequest.setPageSize(10);
        }

        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());

        List<TaskShowDTO> list = taskMapper.findAccepting(userId);
        for (int i = 0; i < list.size(); i++) {
            User user = taskMapper.findByTaskId(list.get(i).getId());
            list.get(i).setNickName(user.getNickName()).setUserId(user.getUserId()).setEmail(user.getUserEmail());
            UserImage image = imageMapper.getOneByUserId(list.get(i).getIsSuerId());
            Integer status = taskMapper.contractStatus(list.get(i).getId(), userId);
            list.get(i).setReceiveTaskStatus(status);
            if (null != image) {
                list.get(i).setImgUrl(image.getImageUrl());
            } else {
                list.get(i).setImgUrl("http://masteryan.oss-cn-beijing.aliyuncs.com/1000000740998476.png");
            }
        }
        return list;
    }

    @Override
    public List<TaskShowDTO> findBySendTaskTypeStatus(PageRequest pageRequest, Long userId) {
        if (EmptyUtil.isEmpty(pageRequest.getPageNum())) {
            pageRequest.setPageNum(1);
        }

        if (EmptyUtil.isEmpty(pageRequest.getPageSize())) {
            pageRequest.setPageSize(10);
        }

        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());

        List<TaskShowDTO> list = taskMapper.findBySendTaskTypeStatus(userId);

        for (int i = 0; i < list.size(); i++) {
            User user = taskMapper.findByTaskId(list.get(i).getId());
            list.get(i).setNickName(user.getNickName()).setUserId(user.getUserId()).setEmail(user.getUserEmail());
            UserImage image = imageMapper.getOneByUserId(list.get(i).getIsSuerId());
            if (null != image) {
                list.get(i).setImgUrl(image.getImageUrl());
            } else {
                list.get(i).setImgUrl("http://masteryan.oss-cn-beijing.aliyuncs.com/1000000740998476.png");
            }
        }
        return list;
    }

    @Override
    public List<TaskShowDTO> findBySendTaskStatus(PageRequest pageRequest, Long userId) {
        if (EmptyUtil.isEmpty(pageRequest.getPageNum())) {
            pageRequest.setPageNum(1);
        }

        if (EmptyUtil.isEmpty(pageRequest.getPageSize())) {
            pageRequest.setPageSize(10);
        }

        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());

        List<TaskShowDTO> list = taskMapper.findBySendTaskStatus(userId);

        for (int i = 0; i < list.size(); i++) {
            User user = taskMapper.findByTaskId(list.get(i).getId());
            list.get(i).setNickName(user.getNickName()).setUserId(user.getUserId()).setEmail(user.getUserEmail());
            UserImage image = imageMapper.getOneByUserId(list.get(i).getIsSuerId());
            if (null != image) {
                list.get(i).setImgUrl(image.getImageUrl());
            } else {
                list.get(i).setImgUrl("http://masteryan.oss-cn-beijing.aliyuncs.com/1000000740998476.png");
            }
        }
        return list;
    }

    @Override
    public List<ProgrammerEntiretyDTO> findAllApplication(PageRequest pageRequest, Long taskId) {
        if (EmptyUtil.isEmpty(pageRequest.getPageNum())) {
            pageRequest.setPageNum(1);
        }

        if (EmptyUtil.isEmpty(pageRequest.getPageSize())) {
            pageRequest.setPageSize(10);
        }

        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());


        List<Long> list = taskMapper.findAllApplication(taskId);

        List<ProgrammerEntiretyDTO> userList = new LinkedList<>();

        for (int i = 0; i < list.size(); i++) {
            ProgrammerEntiretyDTO dto = programmerListService.programmer(list.get(i));
            if (null != dto.getUserId()) {
                userList.add(dto);
            }
        }
        return userList;
    }

    @Override
    public List<TaskShowDTO> findByReceiveTaskUserId(PageRequest pageRequest, Long userId) {
        if (EmptyUtil.isEmpty(pageRequest.getPageNum())) {
            pageRequest.setPageNum(1);
        }

        if (EmptyUtil.isEmpty(pageRequest.getPageSize())) {
            pageRequest.setPageSize(10);
        }

        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());

        List<TaskShowDTO> list = taskMapper.findByReceiveTaskUserId(userId);

        for (int i = 0; i < list.size(); i++) {
            User user = taskMapper.findByTaskId(list.get(i).getId());
            list.get(i).setNickName(user.getNickName()).setUserId(user.getUserId()).setEmail(user.getUserEmail());
            UserImage image = imageMapper.getOneByUserId(list.get(i).getIsSuerId());
            if (null != image) {
                list.get(i).setImgUrl(image.getImageUrl());
            } else {
                list.get(i).setImgUrl("http://masteryan.oss-cn-beijing.aliyuncs.com/1000000740998476.png");
            }
        }
        return list;
    }

    @Override
    public List<TaskShowDTO> findAll(PageRequest pageRequest, HttpServletRequest request, String talentCategories,
                                     String workPlace,
                                     Long workWay, Integer sort) {

        if (EmptyUtil.isEmpty(pageRequest.getPageNum())) {
            pageRequest.setPageNum(1);
        }

        if (EmptyUtil.isEmpty(pageRequest.getPageSize())) {
            pageRequest.setPageSize(10);
        }

        Page<Object> page = PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());

        List<TaskShowDTO> tasks = taskMapper.findAll(talentCategories, workPlace, workWay, sort);

        for (int i = 0; i < Objects.requireNonNull(tasks).size(); i++) {
            String key = getKey(tasks.get(i).getId(), RequestIdUtil.getMyId(request));
            Object obj = redisTemplate.opsForValue().get(key);
            if (null != obj) {
                if ((Integer) obj == 1) {
                    tasks.add(0, tasks.get(i));
                    tasks.remove(i + 1);
                }
            }

        }

        page.setPageSize(pageRequest.getPageSize()).setPageNum(pageRequest.getPageNum());
        return tasks;
    }

    @Override
    public List<ProgrammerCompareDTO> findByList(List<Long> list) {
        List<ProgrammerCompareDTO> programmer = iProgrammerCompareService.listProgrammer(list);

        return programmer;
    }

    @Override
    public Integer findCount(Long taskId) {
        return taskMapper.findCount(taskId);
    }

    @Override
    public Integer insertDelivery(Long taskId, Long userId) {
        Integer exist = taskMapper.findExist(taskId, userId);
        if (exist == 0) {
            return taskMapper.insertDelivery(taskId, userId);
        }
        return 2;

    }

    @Override
    public Integer takeTurn(Long taskId, HttpServletRequest request) {
        String key = getKey(taskId, RequestIdUtil.getMyId(request));
        redisTemplate.opsForValue().set(key, 1);
        redisTemplate.expire(key, 30 * 60, TimeUnit.SECONDS);
        Task task = new Task();
        task.setId(taskId);
        task.setCreateTime(new Date());
        return taskMapper.updateOne(task);
    }

    @Override
    public long taskTotalNumber() {
        return taskMapper.taskTotalNumber();
    }

    @Override
    public ContractDTO contract(Long taskId, Long receiveTaskId, Long sendTaskUserId) {

        Integer exist = taskMapper.taskExist(taskId);
        ContractDTO contract = taskMapper.contract(taskId);
        if (exist == 1) {
            ContractDTO contracts = taskMapper.contracts(taskId);
            contract.setSendTaskUserName(contracts.getSendTaskUserName());
            contract.setReceiveTaskUserId(contracts.getReceiveTaskUserId());
            contract.setStatus(contracts.getStatus());
            contract.setPartyAImageUrl(contracts.getPartyAImageUrl());
            contract.setPartyBImageUrl(contracts.getPartyBImageUrl());
            contract.setStatus(contracts.getStatus());
        }
        Programmer receiveUser = programmerMapper.getOne(receiveTaskId);
        Programmer sendUser = programmerMapper.getOne(sendTaskUserId);
        contract.setSendTaskUserId(sendTaskUserId);
        contract.setReceiveTaskUserId(receiveTaskId);
        contract.setReceiveTaskUserName(receiveUser.getNickName());
        contract.setSendTaskUserName(sendUser.getNickName());
        contract.setTaskId(taskId);
        return contract;

    }

    @Override
    public Integer saveContract(Contract contract) {
        MultipartFile multipart = Base64DecodedMultipartFile.base64ToMultipart(contract.getPartyImage());
        String type = FileUtil.getType(multipart);
        String uuId = UUIDUtil.get16UUId();
        String url = FileServerUtil.uploadFile(multipart, uuId + type);
        contract.setPartyAImageUrl(url);
        return taskMapper.saveContract(contract);
    }

    @Override
    public Integer updatePartBImg(Contract contract) {
        MultipartFile multipart = Base64DecodedMultipartFile.base64ToMultipart(contract.getPartyImage());
        String type = FileUtil.getType(multipart);
        String uuId = UUIDUtil.get16UUId();
        String url = FileServerUtil.uploadFile(multipart, uuId + type);
        contract.setPartyBImageUrl(url);
        Integer img = taskMapper.updatePartBImg(contract);
        if (img == 1) {
            TaskShowDTO dto = taskService.findOne(contract.getTaskId());
            Order order = new Order();
            order.setOrderNum(GenerateOrderNoUtil.getGenerateOrderNo(contract.getPartyAId()));
            order.setSendTaskUserId(contract.getPartyAId());
            order.setReceiveTaskUserId(contract.getPartyBId());
            order.setSalary(dto.getSalary());
            order.setOrderBeginTime(new Date());
            order.setTaskId(contract.getTaskId());
            iOrderService.insertOne(order);
            Task task = new Task();
            task.setId(order.getTaskId());
            task.setTaskStatus(1);
            int one = iTaskService.updateOne(task);

            return 1;
        }
        return 0;
    }

    @Override
    public List<String> getCitys() {
        List<String> citys = taskMapper.getCitys();
        citys.add("其他");
        return citys;
    }

    @Override
    public List<String> getTalentCategory() {
        List<String> talentCategory = taskMapper.getTalentCategory();
        talentCategory.add("其他");
        return talentCategory;
    }

    @Override
    public TaskDTO getOneTask(Long id) {
        return taskMapper.getOneTask(id);
    }


    private static String getKey(Long taskId, Long userId) {
        StringBuilder builder = new StringBuilder();
        builder.append(taskId);
        builder.append("::");
        builder.append(userId);
        return builder.toString();
    }


}
